package com.carbeauty.service.impl;

import com.carbeauty.entity.User;
import com.carbeauty.repository.UserRepository;
import com.carbeauty.service.UserService;
import com.carbeauty.common.enums.UserRole;
import com.carbeauty.common.enums.BusinessStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 用户服务实现类
 * 
 * 实现用户管理的具体业务逻辑:
 * - 用户信息的增删改查
 * - 用户认证和密码管理
 * - 用户状态管理
 * - 数据统计分析
 * 
 * @author CarBeauty Team
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    // ==================== 基础CRUD操作 ====================
    
    @Override
    public User save(User user) {
        // 如果是新用户，加密密码
        if (user.getId() == null && user.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        return userRepository.save(user);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Optional<User> findById(Long id) {
        return userRepository.findById(id);
    }
    
    @Override
    @Transactional(readOnly = true)
    public User getById(Long id) {
        return userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在，ID: " + id));
    }
    
    @Override
    public void deleteById(Long id) {
        User user = getById(id);
        user.delete(); // 逻辑删除
        userRepository.save(user);
    }
    
    @Override
    public void deleteByIds(List<Long> ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
    
    // ==================== 查询操作 ====================
    
    @Override
    @Transactional(readOnly = true)
    public List<User> findAllActive() {
        return userRepository.findByStatusOrderByCreateTimeDesc(BusinessStatus.ACTIVE);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Page<User> findAllActive(Pageable pageable) {
        return userRepository.findAll(pageable);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Optional<User> findByPhone(String phone) {
        return userRepository.findByPhone(phone);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Optional<User> findByEmail(String email) {
        return userRepository.findByEmail(email);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<User> findByRole(UserRole role) {
        return userRepository.findByRole(role);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<User> searchUsers(String username, String realName, String phone, UserRole role, BusinessStatus status) {
        return userRepository.findByConditions(username, realName, phone, role, status);
    }
    
    // ==================== 认证相关 ====================
    
    @Override
    @Transactional(readOnly = true)
    public User login(String username, String password) {
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isEmpty()) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        User user = userOpt.get();
        if (!BusinessStatus.ACTIVE.equals(user.getStatus())) {
            throw new RuntimeException("用户已被禁用");
        }
        
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        return user;
    }
    
    @Override
    public void updateLoginInfo(Long userId, String loginIp) {
        User user = getById(userId);
        user.setLastLoginTime(LocalDateTime.now());
        user.setLastLoginIp(loginIp);
        user.setIsFirstLogin(false);
        userRepository.save(user);
    }
    
    @Override
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        User user = getById(userId);
        
        // 验证旧密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            return false;
        }
        
        // 设置新密码
        user.setPassword(passwordEncoder.encode(newPassword));
        userRepository.save(user);
        
        return true;
    }
    
    @Override
    public void resetPassword(Long userId, String newPassword) {
        User user = getById(userId);
        user.setPassword(passwordEncoder.encode(newPassword));
        user.setIsFirstLogin(true); // 重置密码后需要首次登录
        userRepository.save(user);
    }
    
    // ==================== 用户状态管理 ====================
    
    @Override
    public void enableUser(Long userId) {
        User user = getById(userId);
        user.setStatus(BusinessStatus.ACTIVE);
        userRepository.save(user);
    }
    
    @Override
    public void disableUser(Long userId) {
        User user = getById(userId);
        user.setStatus(BusinessStatus.INACTIVE);
        userRepository.save(user);
    }
    
    @Override
    @Transactional(readOnly = true)
    public boolean isUserActive(Long userId) {
        Optional<User> user = userRepository.findById(userId);
        return user.isPresent() && BusinessStatus.ACTIVE.equals(user.get().getStatus());
    }
    
    // ==================== 数据验证 ====================
    
    @Override
    @Transactional(readOnly = true)
    public boolean isUsernameExists(String username, Long excludeId) {
        Optional<User> user = userRepository.findByUsername(username);
        if (user.isPresent()) {
            return excludeId == null || !user.get().getId().equals(excludeId);
        }
        return false;
    }
    
    @Override
    @Transactional(readOnly = true)
    public boolean isPhoneExists(String phone, Long excludeId) {
        Optional<User> user = userRepository.findByPhone(phone);
        if (user.isPresent()) {
            return excludeId == null || !user.get().getId().equals(excludeId);
        }
        return false;
    }
    
    @Override
    @Transactional(readOnly = true)
    public boolean isEmailExists(String email, Long excludeId) {
        Optional<User> user = userRepository.findByEmail(email);
        if (user.isPresent()) {
            return excludeId == null || !user.get().getId().equals(excludeId);
        }
        return false;
    }
    
    // ==================== 统计分析 ====================
    
    @Override
    @Transactional(readOnly = true)
    public long getTotalUserCount() {
        return userRepository.countByStatus(BusinessStatus.ACTIVE);
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getTodayNewUserCount() {
        return userRepository.countTodayNewUsers();
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getThisMonthNewUserCount() {
        return userRepository.countThisMonthNewUsers();
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Object[]> getUserRoleStatistics() {
        return userRepository.countByRole();
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getOnlineUserCount() {
        // TODO: 实现在线用户统计
        // 可以通过Session管理或者Redis来实现
        return 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<User> findInactiveUsers(int days) {
        LocalDateTime cutoffDate = LocalDateTime.now().minusDays(days);
        return userRepository.findInactiveUsers(cutoffDate);
    }
}
